<?php
namespace app\gym\controller;

use app\common\controller\AdminBase;

/*小型健身房会员管理系统*/
class GymMember extends AdminBase
{
	private $shop_id;

	public function _initialize()
    {
		parent::_initialize();
		$this->shop_id = sp_get_current_shop_id();
    }

	/*列表*/
	public function index()
    {
        $auth_group = sp_get_auth_menu_3("10051001");
		$shop_id = $this->shop_id;
		$this->assign("list", db("GymCard")->where("shop_id=$shop_id and status=1")->field("id,card_name")->select());
		$this->assign("list1", db("GymEmployee")->where("shop_id=$shop_id and status=1 and type=2")->field("id,name")->select());
        $this->assign("menus", $auth_group);
		echo $this->fetch();
	}

    /**
     * 入会
     */
	public function member_in()
    {
		$shop_id=$this->shop_id;
		$this->assign("list1",db("GymEmployee")->where("shop_id=$shop_id and status=1 and type=2")->field("id,name")->select());
		echo $this->fetch();
	}

    /**
     * 入会操作
     */
	public function member_in_post()
    {
		if(request()->isPost()){
			$shop_id = $this->shop_id;
			$name = input("name/s", "");
			$sex = input("sex/d", 1);
            $mobile = input("mobile", 0);
            $id_card = input("id_card", 0);
            $member_ship_id = input("member_ship_id/d", 0);
            $come_from = input("come_from/s", "");
            $birthday = input("birthday/s", "");
            $occupation = input("occupation/s", "");
            $passport = input("passport/s", "");
            $descs = input("descs/s", "");
            $addr = input("addr/s", "");

			if (empty($name)) {
			    $this->ajax_error("姓名不能为空");
            }

            if (mb_strlen($name) > 16) {
			    $this->ajax_error("姓名能超过16个字符");
            }
            if (!in_array($sex, array(1, 2))) {
                $this->ajax_error("性别选择错误");
            }
            if(!preg_match("/^1[3456789]\d{9}$/", $mobile)) {
                $this->ajax_error("手机号格式不正确");
            }
            if (!preg_match("/^\d{15}|\d{18}$/", $id_card)) {
			    $this->ajax_error("身份证号码格式不正确");
            }
            if (empty($member_ship_id)) {
                $this->ajax_error("请选择一个会籍");
            }
            $gym_employee = db("gym_employee")->find($member_ship_id);
			if (empty($gym_employee)) {
			    $this->ajax_error("归属会籍选择错误");
            }
            if ($gym_employee["shop_id"] != $shop_id || $gym_employee["status"] != 1 || $gym_employee["type"] != 2) {
			    $this->ajax_error("归属会籍选择错误");
            }
            $come_from_arr = config("come_from");
            if (!in_array($come_from, $come_from_arr)) {
                $this->ajax_error("会员来源选择错误");
            }


            $count = db("gym_member")->where(array("shop_id" => $shop_id, "mobile" => $mobile))->count(1);
			if ($count > 0) {
				$this->ajax_error("手机号码已经存在");
			}
		    $id = db("gym_member")->insertGetId(array(
				"name"              => $name,
				"birthday"          => $birthday,
				"sex"               => $sex,
				"mobile"            => $mobile,
				"id_card"           => $id_card,
				"occupation"        => $occupation,
				"addr"              => $addr,
				"passport"          => $passport,
				"descs"             => $descs,
				"come_from"         => $come_from,
				"member_ship_id"    => $member_ship_id,
				"shop_id"           => $shop_id,
			));
			//新增一条根据记录
			action("smallapp/FollowUp/add",[input("member_ship_id"),$id,$shop_id]);
			$this->ajax_success("成功",$id);
		}
	}

    /**
     * 购卡
     * @throws \think\db\exception\DataNotFoundException
     * @throws \think\db\exception\ModelNotFoundException
     * @throws \think\exception\DbException
     */
	public function buy_card()
    {
		$shop_id=$this->shop_id;
		$id=input("id",0);
        $pvalue=db("SystemSet")->where(" shop_id=$shop_id  and code='s_s_6' ")->value("pvalue");
        if(empty($pvalue)){
            $this->assign("machines","");
        }elseif($pvalue==1){
            $this->assign("machines","<option value='1' selected >指纹验证</option>");
        }elseif($pvalue==2){
            $this->assign("machines","<option value='2' selected >人脸验证</option>");
        } elseif($pvalue==4){
            $this->assign("machines","<option value='1' selected >指纹验证</option><option value='2' >人脸验证</option>");
        }
		$this->assign("model",db("GymMember")->where("shop_id=$shop_id and id=$id")->find());
		$this->assign("cards",db("GymCard")->where("shop_id=$shop_id and status=1")->select());
		$this->assign("gifts",db("GymGift")->where("shop_id=$shop_id and status=1")->select());
		echo $this->fetch();
	}

    /**
     * 购卡操作
     */
	public function buy_card_post()
    {
		if (request()->isPost()) {
			$shop_id                = $this->shop_id;
			$gym_member_id          = input("gym_member_id");
			$card_no                = input("card_no/s", "");
            $gym_card_id            = input("gym_card_id/d", 0);
            $pay_type               = input("pay_type/s", "");
            $come_from              = input("come_from/s", "");
            $order_date             = input("order_date/s", date("Y-m-d"));
            $activate_type          = input("activate_type/d", 0);
            $gift_id                = input("gift_id/s", 0);
            $descs                  = input("descs/s", "");
            $in_varifycation        = input("in_varifycation/d", 0);
            $in_varifycation_type   = input("in_varifycation_type/d", 0); //验证类型：0不验证 1指纹验证 2人脸验证 3前台验证
            if (empty($gym_member_id)) {
                $this->error("参数错误");
            }
            if (empty($card_no)) {
                $this->ajax_error("卡号不能为空");
            }
            if (empty($gym_card_id)) {
                $this->ajax_error("卡种不能为空");
            }
            if (empty($pay_type)) {
                $this->ajax_error("支付方式不能为空");
            }
            if (empty($come_from)) {
                $this->ajax_error("合同来源不能为空");
            }
            if (empty($order_date)) {
                $this->ajax_error("签约日期不能为空");
            }
            if (empty($activate_type)) {
                $this->ajax_error("开卡方式不能为空");
            }


            $gym_member = db("gym_member")->find($gym_member_id);
            if (empty($gym_member) || $gym_member["shop_id"] != $shop_id) {
                $this->error("用户不存在");
            }
            $card_is_exist = db("interface")->where(array("card_no" => $card_no, "shop_id" => $shop_id))->count(1);
            if (!empty($card_is_exist)) {
                $this->ajax_error("卡号已存在");
            }

            if (!preg_match("/^\d{10}$/", $card_no)) { //卡号只能位10位数字
                $this->ajax_error("卡号只能位10位数字");
            }

            $gym_card = db("gym_card")->find($gym_card_id);
            if (empty($gym_card)) {
                $this->ajax_error("所选卡种不存在");
            }

            if ($gym_card["shop_id"] != $shop_id || empty($gym_card["status"])) {
                $this->ajax_error("所选卡种不存在");
            }
            if (!in_array($in_varifycation, array(0, 1))) {
                $this->ajax_error("验证方式选择错误");
            }
            if (!in_array($in_varifycation_type, array(0, 1, 2, 3))) { //验证类型：0不验证 1指纹验证 2人脸验证 3前台验证
                $this->ajax_error("验证方式选择错误");
            }

            $pay_types = config("pay_type");
            if (!in_array($pay_type, $pay_types)) {
                $this->ajax_error("支付方式选择错误");
            }

            $come_from_arr = config("come_from");
            if (!in_array($come_from, $come_from_arr)) {
                $this->ajax_error("合同来源选择错误");
            }

            if (!in_array($activate_type, array(1, 2))) { //开卡方式： 1立即开卡 2延迟开卡
                $this->ajax_error("开卡方式选择错误");
            }
            if (!empty($gift_id)) {
                $gift = db("gym_gift")->find($gift_id);
                if (empty($gift)) {
                    $this->ajax_error("礼物不存在");
                }
                if (empty($gift['status']) || $gift['shop_id'] != $shop_id) {
                    $this->ajax_error("礼物不存在");
                }
                $gift_name = $gift["name"];
            }

            //order数据
            $order_arr = array(
               "order_no"           => $this->getUniqueOrderNo(),
               "card_no"            => $card_no,
               "activate_type"      => $activate_type,
               "pay_money"          => $gym_card["price"],
               "pay_type"           => $pay_type,
               "come_from"          => $come_from,
               "order_date"         => $order_date,
               "member_ship_id"     => $gym_member["member_ship_id"],
               "old_member_ship_id" => $gym_member["member_ship_id"],
               "shop_id"            => $shop_id,
               "descs"              => $descs,
               "gift_id"            => $gift_id,
               "gift"               => empty($gift_name) ? "无" : $gift_name,
               "gym_card_name"      => $gym_card["card_name"],
               "gym_card_type"      => $gym_card["card_type"],
               "able_count"         => $gym_card["able_count"],
               "able_money"         => $gym_card["able_money"],
               "gym_card_id"        => $gym_card_id,
               "admin_id"           => sp_get_current_admin_id(),
               'order_status'       => 1,
               "gym_member_id"      => $gym_member_id,
               "time_sets"          => empty($gym_card["time_sets"]) ? "" : $gym_card["time_sets"],
           );
            if ($activate_type == 1) { //立即激活
                $order_arr['activate_date']= $order_date;
                $order_arr['start_date'] = $order_date;
                $order_arr['order_status'] = 1;
            } else if ($activate_type == 2) { //延迟激活
                $activate_date = input("activate_date/s");
                if(empty($activate_date)) {
                    $order_arr['activate_date'] = $order_date;
                } else {
                    $order_arr['activate_date'] = $activate_date;
                }
                $order_arr['start_date'] = $order_arr['activate_date'];
                if(strcmp($order_arr['activate_date'], date("Y-m-d")) > 0 ) {
                    $order_arr['order_status'] = 3;
                }
            }
            $end_date_str = $order_arr['start_date'] . " + " . "{$gym_card['expiry_date']} day";
            $order_arr['end_date'] = date("Y-m-d", strtotime($end_date_str));
            $order_arr['able_day'] = $this->_get_able_day($order_arr['start_date'], $order_arr['end_date']);

            $member_arr = array(
                "card_no"           => $card_no,
                "in_varifycation"   => $in_varifycation,
                "start_date"        => $order_arr["start_date"],
                "end_date"          => $order_arr["end_date"],
                "mobile"            => $gym_member["mobile"],
                "contract_id"       => $order_arr["order_no"],
                "member_id"         => $gym_member_id,
                "name"              => $gym_member["name"],
                "surplus_num"       => $order_arr["able_count"],
                "membership_type"   => $order_arr["gym_card_type"],
                "contract_status"   => $order_arr["order_status"],
                "owner_type"        => 1, //会员卡
                "shop_id"           => $shop_id,
            );
            $member_arr["in_varifycation_type"] = $in_varifycation_type;
            if ($in_varifycation == 1) {//需要验证
                if ($in_varifycation_type == 1) { //指纹验证
                    $finger_print = input("fingerprint/s");
                    if (empty($finger_print)) {
                        $this->error("指纹未录入成功");
                    }
                    $member_arr["fingerprint"] = $finger_print;
                    $this->_model_down_record_save_update(array("shop_id" => $shop_id, "card_no" => $card_no, "type" => 1));
                } else if ($in_varifycation_type == 2) {//人脸验证
                    $this->_face_code_insertOrupdate(array(
                        "card_no"   => $card_no,
                        "face1"     => input("face1"),
                        "icon1"     => input("icon1"),
                        "shop_id"   => $shop_id,
                    ));
                }
            } else {
                $member_arr["in_varifycation_type"] = 0;
            }



            //新增订单
            $order_id = db("gym_order")->insertGetId($order_arr);
            //新增购卡历史记录
            $order_arr['id'] = $order_id;
            $this->addOrderHistory(1, $order_arr); //type: 操作类型：1购卡 2升级 3续卡 4退款重办 5退会 6换卡 7转卡 8请假 9销假

            //新增会员信息到ic设备中
            db("gym_member")->where(array("id" => $gym_member_id))->setField(array("web_open_up" => 1));
            db("interface")->insert($member_arr);

            //记录员工业绩
            $this->employeeAchievement($gym_card["price"], $gym_member["member_ship_id"], $shop_id);

			$this->ajax_success("成功");
		}else{
			$this->ajax_error("error");
		}		
	}

	/**
	 * 升级+自定义组合
	 */
	public function member_up()
    {
		$shop_id = $this->shop_id;
		$id = input("order_id/d",0);
		if (empty($id)) {
		    $this->ajax_tpl("参数错误");
        }
		$order = db("gym_order")->where(array("shop_id" => $shop_id, "id" => $id, "is_delete" => 0))->find();
		if (empty($order)) {
		    $this->ajax_tpl("参数错误");
        }
		$member = db("gym_member")->where(array("id" => $order["gym_member_id"]))->find();

	    $this->assign("order", $order);
		$this->assign("member", $member);

		$this->assign("employees", db("gym_employee")->where(array("shop_id" => $shop_id, "status" => 1, "type" => 2))->field("id, name")->select());
		
		if($order['gym_card_type'] == 2 || $order['gym_card_type'] == 4) {//期限卡/错峰卡
			$this->assign("able_day", $this->_get_able_day($order['start_date'], $order['end_date']));
		}
		echo $this->fetch();
	}

	private function _get_able_day($start,$end)
    {
	   if(strcmp($start,$end)<0){
	   	   if(strcmp(date("Y-m-d"),$start)<0){//未开卡
	   	   		$day=(strtotime("$end")-strtotime("$start"))/(24*60*60); 
	   	   } else if (strcmp(date("Y-m-d"),$end) > 0) {
	   	       $day = 0;
           } else{
	   	   	   $day=(strtotime("$end")-strtotime(date("Y-m-d")))/(24*60*60);
	   	   }
	   }else{
	   	  $day=0;
	   }	
	   return $day;
	}

    /**
     * 升级操作
     * @throws \think\Exception
     * @throws \think\db\exception\DataNotFoundException
     * @throws \think\db\exception\ModelNotFoundException
     * @throws \think\exception\DbException
     * @throws \think\exception\PDOException
     */
	public function member_up_post()
    {
		if(request()->isPost()){
            $shop_id = $this->shop_id;
            $id = input("order_id/d",0);
            $end_date = input("end_date", date("Y-m-d"));
            $pay_money = input("pay_money", 0);
            $pay_type = input("pay_type/s");
            $order_date = input("order_date", date("Y-m-d"));
            $descs = input("descs");
            if (strtotime($end_date) < (time() - 86400)) {
               $this->ajax_error("有效期结束不能小于今天");
            }
            if (empty($pay_money)) {
                $this->ajax_error("支付金额不能为空");
            }
            if (empty($pay_type)) {
                $this->ajax_error("支付方式不能为空");
            }
            $pay_types = config("pay_type");
            if (!in_array($pay_type, $pay_types)) {
                $this->ajax_error("支付方式选择错误");
            }

            if (empty($id)) {
                $this->error("参数错误");
            }
            $order_old = db("gym_order")->where(array("shop_id" => $shop_id, "id" => $id, "is_delete" => 0))->find();
            if (empty($order_old)) {
                $this->error("参数错误");
            }

			$data = array(
			        'order_no'      => $this->getUniqueOrderNo(),
					"end_date"      => $end_date,
					"pay_money"     => $pay_money,
					"pay_type"      => $pay_type,
					"order_date"    => $order_date,
					"descs"         => $descs,
					"admin_id"      => sp_get_current_admin_id(),
				);
            if ($order_old["gym_card_type"] == 2 || $order_old["gym_card_type"] == 4) { //期限卡 /错峰卡
                $data['able_day'] = input("able_day/d", 0);
            } elseif ($order_old["gym_card_type"] == 1) { //次卡
                $data['able_count'] = input("able_count/d", 0);
                $data["buy_count"] = input("able_count/d", 0);
            } elseif ($order_old["gym_card_type"] == 3) { //储值卡
                $data['able_money'] = input("able_money/f", 0);
            }

			db("gym_order")->where(array("id" => $id))->update($data);
			//新增升级历史记录

            $order_old['able_day'] = $this->_get_able_day(date("Y-m-d"), $order_old['end_date']);
            $this->addOrderHistory(2, $data, $order_old); //type:1购卡 2升级 3续卡 4退款重办 5退会 6换卡 7转卡 8请假 9销假

            //记录员工业绩
            $this->employeeAchievement($pay_money, $order_old["member_ship_id"], $shop_id);
			
			$this->ajax_success("成功");
		}
	}

    /**
     * 续卡+同类型的卡种
     * @throws \think\db\exception\DataNotFoundException
     * @throws \think\db\exception\ModelNotFoundException
     * @throws \think\exception\DbException
     */
	public function member_continu()
    {
		$id = input("order_id",0);
        $shop_id = $this->shop_id;
        if (empty($id)) {
            $this->ajax_tpl("参数错误");
        }
        $order = db("gym_order")->where(array("shop_id" => $shop_id, "id" => $id, "is_delete" => 0))->find();
        if (empty($order)) {
            $this->ajax_tpl("参数错误");
        }
        $member = db("gym_member")->where(array("id" => $order["gym_member_id"]))->find();

	    $this->assign("order", $order);
		$this->assign("member", $member);
		$this->assign("employees", db("gym_employee")->where(array("shop_id" => $shop_id, "status" => 1, "type" => 2))->field("id, name")->select());
		$this->assign("cards",db("gym_card")->where(array("shop_id" => $shop_id, "status" => 1, "card_type" => $order["gym_card_type"]))->select());
		echo $this->fetch();
	}

    /**
     * 续卡操作
     * @throws \think\Exception
     * @throws \think\db\exception\DataNotFoundException
     * @throws \think\db\exception\ModelNotFoundException
     * @throws \think\exception\DbException
     * @throws \think\exception\PDOException
     */
	public function member_continu_post()
    {
		if(request()->isPost()){
            $id = input("order_id/d",0);
            $gym_card_id = input("gym_card_id/d", 0);
            $pay_type = input("pay_type/s", "");
            $order_date = input("order_date/s", date("Y-m-d"));
            $descs = input("descs/s", "");
            $shop_id = $this->shop_id;
            if (empty($id)) {
                $this->ajax_error("参数错误");
            }
            if (empty($gym_card_id)) {
                $this->ajax_error("请选择卡种");
            }
            if (empty($pay_type)) {
                $this->ajax_error("支付方式不能为空");
            }
            if (empty($order_date)) {
                $this->error("签约方式不能为空");
            }

            $gym_card = db("gym_card")->find($gym_card_id);
            $order_old = db("gym_order")->where(array("shop_id" => $shop_id, "id" => $id, "is_delete" => 0))->find();
            if (empty($gym_card)) {
                $this->ajax_error("卡种不存在");
            }
            if (empty($order_old)) {
                $this->ajax_error("参数错误");
            }
            if ($gym_card["shop_id"] != $shop_id || $gym_card["status"] != 1 || $gym_card["card_type"] != $order_old["gym_card_type"]) {
                $this->ajax_error("卡种不存在");
            }
            $pay_types = config("pay_type");
            if (!in_array($pay_type, $pay_types)) {
                $this->ajax_error("支付方式选择错误");
            }


			$data = array(
			    "order_no"      => $this->getUniqueOrderNo(),
                "gym_card_id"   => $gym_card_id,
                "pay_type"      => $pay_type,
                "order_date"    => $order_date,
                "descs"         => $descs,
                "pay_money"     => $gym_card["price"],
                "admin_id"      => sp_get_current_admin_id(),
                "gym_card_name" => $gym_card["card_name"]
				);
            $end_date_str = $order_old['end_date'] . " + " . "{$gym_card['expiry_date']} day";
            $data['end_date'] = date("Y-m-d", strtotime($end_date_str));
            $data['able_day'] = $order_old['able_day'] + $gym_card['expiry_date'];

			if ($gym_card["card_type"] == 1) { //次卡
				$data['able_count'] = $order_old["able_count"] + $gym_card["able_count"];
				$data['buy_count'] = $gym_card["able_count"];
			} elseif ($gym_card["card_type"] == 3) { //储值卡
				$data['able_money'] = $order_old["able_money"] + $gym_card["able_money"];
			}

            db("gym_order")->where(array("id" => $id))->update($data);
            //新增升级历史记录
            $this->addOrderHistory(3, $data, $order_old); //type:1购卡 2升级 3续卡 4退款重办 5退会 6换卡 7转卡 8请假 9销假

            //记录员工业绩
            $this->employeeAchievement($gym_card["price"], $order_old["member_ship_id"], $shop_id);

            $this->ajax_success("成功");
		}
	}


    /**
     * 退款重办理
     * @throws \think\db\exception\DataNotFoundException
     * @throws \think\db\exception\ModelNotFoundException
     * @throws \think\exception\DbException
     */
	public function member_in_again()
    {
        $id = input("order_id/d",0);
        $shop_id = $this->shop_id;
        if (empty($id)) {
            $this->ajax_tpl("参数错误");
        }
        $order = db("gym_order")->where(array("shop_id" => $shop_id, "id" => $id, "is_delete" => 0))->find();
        $order_history = db("gym_order_history")->where(array("shop_id" => $shop_id, "order_id" => $id))->order("id desc")->find();
        if (!($order_history["operation_type"] == 1 || $order_history["opt_type"] == "购卡")) {
            $this->ajax_tpl("该卡已进行升级或续约等操作，不能退款重办");
        }
        if (empty($order)) {
            $this->ajax_tpl("参数错误");
        }
        $member = db("gym_member")->where(array("id" => $order["gym_member_id"]))->find();

        $this->assign("order", $order);
        $this->assign("member", $member);
        $this->assign("able_day",$this->_get_able_day($order['start_date'],$order['end_date']));
        $this->assign("employees", db("gym_employee")->where(array("shop_id" => $shop_id, "status" => 1, "type" => 2))->field("id, name")->select());
        echo $this->fetch();
	}

    /**
     * 退款重办理操作
     * @throws \think\Exception
     * @throws \think\db\exception\DataNotFoundException
     * @throws \think\db\exception\ModelNotFoundException
     * @throws \think\exception\DbException
     * @throws \think\exception\PDOException
     */
	public function member_in_again_post()
    {
        $id = input("order_id/d",0);
        $shop_id = $this->shop_id;
        $order_date = input("order_date/s", date("Y-m-d"));
        $descs = input("descs/s", "");
        if (empty($id)) {
            $this->ajax_error("参数错误");
        }
        $order_old = db("gym_order")->where(array("shop_id" => $shop_id, "id" => $id, "is_delete" => 0))->find();
        $order_history = db("gym_order_history")->where(array("shop_id" => $shop_id, "order_id" => $id))->order("id desc")->find();
        if (!($order_history["operation_type"] == 1 || $order_history["opt_type"] == "购卡")) {
            $this->ajax_error("该卡已进行升级或续约等操作，不能退款重办");
        }
        if (empty($order_old)) {
            $this->ajax_error("参数错误");
        }
        $data = array(
            "order_date"    => $order_date,
            "descs"         => $descs,
            "order_status"  => 0, //修改订单状态
            "is_delete"     => 1
        );
		//新增退款重新办理记录
        $this->addOrderHistory(4, $data, $order_old); //type:1购卡 2升级 3续卡 4退款重办 5退会 6换卡 7转卡 8请假 9销假
		//清除interface 中的数据
        db("interface")->where(array("shop_id" => $shop_id, "card_no" => $order_old["card_no"]))->delete(); //闸机接口表
        db("face_code")->where(array("shop_id" => $shop_id, "card_no" => $order_old["card_no"]))->delete(); //人脸特征码
		db("gym_order")->where(array("id" => $id))->update($data);

        //记录员工业绩
        $this->employeeAchievement(-$order_old["pay_money"], $order_old["member_ship_id"], $shop_id);

		$this->ajax_success("成功");
	}

	/**
	 * 是否有私教课
	 * */
	public function has_private_lesson()
    {
		//判断是否有私教课
        $shop_id = $this->shop_id;
		$id = input("id/d",0);
		$gym_order_count = db("gym_order")->where(array("gym_member_id" => $id, "is_delete" => 0, "shop_id" => $shop_id))->count(1);
		if(empty($gym_order_count)) {
		    $this->ajax_error("该会员没有购卡");
        }
		//只有一张卡的情况下才去判断是否有私教课
        if ($gym_order_count == 1) {
            $has_private_lesson = db("GymPtOrder")->where(array("member_id" => $id, "status" => 1))->count(1);
            if(!empty($has_private_lesson)){
                return  $this->ajax_error("该会员有私教课程，请先去退课！");
            }
        }
        return  $this->ajax_success("");
	}

    /**
     * 退会
     * @throws \think\db\exception\DataNotFoundException
     * @throws \think\db\exception\ModelNotFoundException
     * @throws \think\exception\DbException
     */
	public function member_out()
    {
        $id = input("order_id/d",0);
        $shop_id = $this->shop_id;
        if (empty($id)) {
            $this->ajax_tpl("参数错误");
        }
        $order = db("gym_order")->where(array("shop_id" => $shop_id, "id" => $id, "is_delete" => 0))->find();
        if (empty($order)) {
            $this->ajax_tpl("参数错误");
        }
        $member = db("gym_member")->where(array("id" => $order["gym_member_id"]))->find();

	    $this->assign("order", $order);
		$this->assign("member", $member);
		$this->assign("able_day",$this->_get_able_day($order['start_date'],$order['end_date']));
		echo $this->fetch();
	}

    /**
     * 退会操作
     * @throws \think\Exception
     * @throws \think\db\exception\DataNotFoundException
     * @throws \think\db\exception\ModelNotFoundException
     * @throws \think\exception\DbException
     * @throws \think\exception\PDOException
     */
	public function  member_out_post()
    {
        $id = input("order_id/d",0);
        $shop_id = $this->shop_id;
        if (empty($id)) {
            $this->ajax_error("参数错误");
        }
        $order = db("gym_order")->where(array("shop_id" => $shop_id, "id" => $id, "is_delete" => 0))->find();
        if (empty($order)) {
            $this->ajax_error("参数错误");
        }

        $gym_order_count = db("gym_order")->where(array("gym_member_id" => $order["gym_member_id"], "is_delete" => 0))->count(1);
        if(empty($gym_order_count)) {
            $this->ajax_error("该会员没有购卡");
        }
        //只有一张卡的情况下才去判断是否有私教课
        if ($gym_order_count == 1) {
            $has_private_lesson = db("GymPtOrder")->where(array("member_id" => $id, "status" => 1))->count(1);
            if(!empty($has_private_lesson)){
                return  $this->ajax_error("该会员有私教课程，请先去退课！");
            }
        }

        $pay_money = input("refund/f", 0);
        $order_date = input("order_date/s", date("Y-m-d"));
        $pay_type = input("refund_type/s", "");
        $descs = input("descs/s", "");

        if (empty($pay_type)) {
            $this->ajax_error("支付方式不能为空");
        }
        $pay_types = config("pay_type");
        if (!in_array($pay_type, $pay_types)) {
            $this->ajax_error("支付方式选择错误");
        }

		//新增退会记录
		$data = array(
            "pay_money" => $pay_money,
            "pay_type"  => $pay_type,
            "descs"     => $descs,
            "order_date"=> $order_date,
            "order_no"  => $this->getUniqueOrderNo(),
            "order_status" => 0,
            "is_delete" => 1
        );
        //新增退款重新办理记录
        $this->addOrderHistory(5, $data, $order); //type:1购卡 2升级 3续卡 4退款重办 5退会 6换卡 7转卡 8请假 9销假
        //清除interface 中的数据
        db("interface")->where(array("shop_id" => $shop_id, "card_no" => $order["card_no"]))->delete(); //闸机接口表
        db("face_code")->where(array("shop_id" => $shop_id, "card_no" => $order["card_no"]))->delete(); //人脸特征码
        db("gym_order")->where(array("id" => $id))->update($data);

        //记录员工业绩
        $this->employeeAchievement(-$pay_money, $order["member_ship_id"], $shop_id);

		$this->ajax_success("成功");
	}


    /**
     * 换卡
     * @throws \think\db\exception\DataNotFoundException
     * @throws \think\db\exception\ModelNotFoundException
     * @throws \think\exception\DbException
     */
	public function member_change_card()
    {
        $id = input("order_id/d",0);
        $shop_id = $this->shop_id;
        if (empty($id)) {
            $this->ajax_tpl("参数错误");
        }
        $order = db("gym_order")->where(array("shop_id" => $shop_id, "id" => $id, "is_delete" => 0))->find();
        if (empty($order)) {
            $this->ajax_tpl("参数错误");
        }
        $member = db("gym_member")->where(array("id" => $order["gym_member_id"]))->find();

	    $this->assign("order",$order);
		$this->assign("member",$member);	
		echo $this->fetch();
	}


    /**
     * 换卡操作
     * @throws \think\Exception
     * @throws \think\db\exception\DataNotFoundException
     * @throws \think\db\exception\ModelNotFoundException
     * @throws \think\exception\DbException
     * @throws \think\exception\PDOException
     */
	public function member_change_card_post()
    {
		if(request()->isPost()){
			$id = input("order_id/d");
			$shop_id = $this->shop_id;
			$card_no = input("card_no");
			$pay_money = input("pay_money/f", 0);
			$pay_type = input("pay_type/s", "");
			$order_date = input("order_date", "Y-m-d");
			$descs = input("descs/s", "");
            if (empty($id)) {
                $this->ajax_error("参数错误");
            }
            if (empty($card_no)) {
                $this->ajax_error("卡号不能为空");
            }
            if (empty($pay_type)) {
                $this->ajax_error("支出方式不能为空");
            }
            $order_old = db("gym_order")->where(array("shop_id" => $shop_id, "id" => $id, "is_delete" => 0))->find();
            if (empty($order_old)) {
                $this->ajax_error("未找到该卡");
            }
			if ($card_no == $order_old["card_no"]) {
				 $this->ajax_error("新卡号和旧卡号不能相同");
			}
            if (!preg_match("/^\d{10}$/", $card_no)) { //卡号只能位10位数字
                $this->ajax_error("卡号只能位10位数字");
            }
            $pay_types = config("pay_type");
            if (!in_array($pay_type, $pay_types)) {
                $this->ajax_error("支付方式选择错误");
            }


			$count = db("interface")->where(array("shop_id" => $shop_id, "card_no" => $card_no))->count(1);
			if ($count > 0) {
				 $this->ajax_error("卡号已经存在");
			}

			$data = array(
					"order_no" => $this->getUniqueOrderNo(),
					"pay_money" => $pay_money,
					"pay_type" => $pay_type,
					"order_date" => $order_date,
					"descs" => $descs,
					"admin_id" => sp_get_current_admin_id(),
					"card_no" => $card_no,
				);

			//添加换卡记录历史记录
			$this->addOrderHistory(6, $data, $order_old); //type:1购卡 2升级 3续卡 4退款重办 5退会 6换卡 7转卡 8请假 9销假
			//修改interface
			db("interface")->where(array("shop_id" => $shop_id, "card_no" => $order_old["card_no"]))->setField(array("card_no" => $card_no));
            db("face_code")->where(array("shop_id" => $shop_id, "card_no" => $order_old["card_no"]))->setField(array("card_no" => $card_no)); //人脸特征码
				
			db("gym_order")->where(array("id" => $id))->update($data);

            //记录员工业绩
//            $this->employeeAchievement($pay_money, $order_old["member_ship_id"], $shop_id);
			
			$this->ajax_success("成功");
		}
	}

    /**
     * 转卡
     * @throws \think\db\exception\DataNotFoundException
     * @throws \think\db\exception\ModelNotFoundException
     * @throws \think\exception\DbException
     */
	public function member_trans()
    {
        $id = input("order_id/d",0);
        $shop_id = $this->shop_id;
        if (empty($id)) {
            $this->ajax_tpl("参数错误");
        }
        $order = db("gym_order")->where(array("shop_id" => $shop_id, "id" => $id, "is_delete" => 0))->find();
        if (empty($order)) {
            $this->ajax_tpl("参数错误");
        }
        $member = db("gym_member")->where(array("id" => $order["gym_member_id"]))->find();
	    $this->assign("order",$order);
		$this->assign("member",$member);	
		echo $this->fetch();
	}

    /**
     * 转卡操作
     * @throws \think\Exception
     * @throws \think\db\exception\DataNotFoundException
     * @throws \think\db\exception\ModelNotFoundException
     * @throws \think\exception\DbException
     * @throws \think\exception\PDOException
     */
	public function member_trans_post()
    {
		if (request()->isPost()) {
            $id = input("order_id/d");
            $shop_id = $this->shop_id;
            $pay_money = input("pay_money/f", 0);
            $pay_type = input("pay_type/s", "");
            $order_date = input("order_date", "Y-m-d");
            $descs = input("descs/s", "");
            $gym_member_id = input("gym_member_id/d");

            if (empty($id)) {
                $this->ajax_error("参数错误");
            }
            if (empty($pay_type)) {
                $this->ajax_error("支出方式不能为空");
            }
            if (empty($gym_member_id)) {
                $this->ajax_error("转入会员不能为空");
            }
            $order_old = db("gym_order")->where(array("shop_id" => $shop_id, "id" => $id, "is_delete" => 0))->find();
            if (empty($order_old)) {
                $this->ajax_error("未找到该卡");
            }
            $pay_types = config("pay_type");
            if (!in_array($pay_type, $pay_types)) {
                $this->ajax_error("支付方式选择错误");
            }

            //验证用户
            $gym_member = db("gym_member")->find($gym_member_id);
            if (empty($gym_member)) {
                $this->ajax_error("用户不存在");
            }
            //限制卡不能自己转自己
            if ($gym_member_id == $order_old['gym_member_id']) {
                $this->ajax_error("不能自己转给自己");
            }

			$data = array(
					"order_no"          => $this->getUniqueOrderNo(),
					"gym_member_id"     => $gym_member_id,
					"pay_type"          => $pay_type,
					"pay_money"         => $pay_money,
					"order_date"        => $order_date,
					"descs"             => $descs,
					"member_ship_id"    => $gym_member["member_ship_id"],
					"old_member_ship_id" => $order_old["member_ship_id"],
					"admin_id"          => sp_get_current_admin_id()
				);


            $this->addOrderHistory(7, $data, $order_old); //type:1购卡 2升级 3续卡 4退款重办 5退会 6换卡 7转卡 8请假 9销假

            //重新生成interface
            $interface =  db("interface")->where(array("shop_id" => $shop_id, "card_no" => $order_old["card_no"]))->find();
            $interface_data = array(
                "mobile" => $gym_member['mobile'],
                "contract_id" => $data['order_no'],
                "member_id" =>$gym_member['id'],
                "name" => $gym_member['name']
            );
            if (!empty($interface["in_varifycation"])) {
                $interface_data["in_varifycation_type"] = 3;
            }

            db("interface")->where(array("shop_id" => $shop_id, "card_no" => $order_old["card_no"]))->setField($interface_data);
            //删除face_code

            db("face_code")->where(array("shop_id" => $shop_id, "card_no" => $order_old["card_no"]))->delete(); //人脸特征码
			db("gym_order")->where("id=$id and shop_id=$shop_id")->update($data);

            //记录员工业绩
//            $this->employeeAchievement($pay_money, $gym_member["member_ship_id"], $shop_id);

			$this->ajax_success("成功");
		}
	}

    /**
     * 请假
     * @throws \think\db\exception\DataNotFoundException
     * @throws \think\db\exception\ModelNotFoundException
     * @throws \think\exception\DbException
     */
	public function member_leave()
    {
        $id = input("order_id/d",0);
        $shop_id = $this->shop_id;
        if (empty($id)) {
            $this->ajax_tpl("参数错误");
        }
        $order = db("gym_order")->where(array("shop_id" => $shop_id, "id" => $id, "is_delete" => 0))->find();
        if (empty($order)) {
            $this->ajax_tpl("参数错误");
        }
        if ($order["order_status"] == 3) {
            $this->ajax_tpl("此会员没有激活，无法请假");
        }
        $member = db("gym_member")->where(array("id" => $order["gym_member_id"]))->find();
	    $this->assign("order", $order);
		$this->assign("member", $member);
		echo $this->fetch();
	}

    /**
     * 请假操作
     * @throws \think\Exception
     * @throws \think\db\exception\DataNotFoundException
     * @throws \think\db\exception\ModelNotFoundException
     * @throws \think\exception\DbException
     * @throws \think\exception\PDOException
     */
	public function member_leave_post()
    {
		if(request()->isPost()){
            $id = input("order_id/d");
            $shop_id = $this->shop_id;
            $pay_money = input("pay_money/f", 0);
            $pay_type = input("pay_type/s", "");
            $order_date = input("order_date", "Y-m-d");
            $descs = input("descs/s", "");
            $leave_day=input("leave_day/d",0);

            if (empty($id)) {
                $this->ajax_error("参数错误");
            }
            if (empty($pay_type)) {
                $this->ajax_error("支出方式不能为空");
            }

            $order_old = db("gym_order")->where(array("shop_id" => $shop_id, "id" => $id, "is_delete" => 0))->find();
            if (empty($order_old)) {
                $this->ajax_error("未找到该卡");
            }
            $pay_types = config("pay_type");
            if (!in_array($pay_type, $pay_types)) {
                $this->ajax_error("支付方式选择错误");
            }
            $end_date = date("Y-m-d", strtotime("{$order_old['end_date']} + {$leave_day} day"));

			$data = array(
					"order_no"      => $this->getUniqueOrderNo(),
					"end_date"      => $end_date,
					"pay_type"      => $pay_type,
					"pay_money"     => $pay_money,
					"order_date"    => $order_date,
					"descs"         => $descs,
					"admin_id"      => sp_get_current_admin_id(),
					"order_status"  => 4,
				);
			//添加请假记录历史记录	
            $this->addOrderHistory(8, $data, $order_old); //type:1购卡 2升级 3续卡 4退款重办 5退会 6换卡 7转卡 8请假 9销假

			unset($data["pay_money"]);

			db("gym_order")->where(array("id" => $id))->update($data);

            //记录员工业绩
//            $this->employeeAchievement($pay_money, $order_old["member_ship_id"], $shop_id);

			$this->ajax_success("成功");
		}
	}

    /**
     * 销假
     * @throws \think\db\exception\DataNotFoundException
     * @throws \think\db\exception\ModelNotFoundException
     * @throws \think\exception\DbException
     */
	public function member_sick_leave()
    {
        $id = input("order_id/d",0);
        $shop_id = $this->shop_id;
        if (empty($id)) {
            $this->ajax_tpl("参数错误");
        }
        $order = db("gym_order")->where(array("shop_id" => $shop_id, "id" => $id, "is_delete" => 0))->find();
        if (empty($order)) {
            $this->ajax_tpl("参数错误");
        }
        if ($order['order_status'] != 4) {
            $this->ajax_tpl("此会员没有请假，无需销假");
        }
        $member = db("gym_member")->where(array("id" => $order["gym_member_id"]))->find();
	    $this->assign("order", $order);
		$this->assign("member", $member);
		echo $this->fetch();
	}

    /**
     * 销假操作
     * @throws \think\Exception
     * @throws \think\db\exception\DataNotFoundException
     * @throws \think\db\exception\ModelNotFoundException
     * @throws \think\exception\DbException
     * @throws \think\exception\PDOException
     */
	public function member_sick_leave_post()
    {
		if(request()->isPost()){
            $id = input("order_id/d");
            $shop_id = $this->shop_id;
            $descs = input("descs/s", "");

            if (empty($id)) {
                $this->ajax_error("参数错误");
            }
            $order_old = db("gym_order")->where(array("shop_id" => $shop_id, "id" => $id, "is_delete" => 0))->find();
            if (empty($order_old)) {
                $this->ajax_error("未找到该卡");
            }

			$data=array(
					"order_no"      => $this->getUniqueOrderNo(),
					"descs"         => $descs,
					"admin_id"      => sp_get_current_admin_id(),
					"order_status"  => 1,
				);
            $this->addOrderHistory(9, array_merge($order_old, $data), $order_old); //type:1购卡 2升级 3续卡 4退款重办 5退会 6换卡 7转卡 8请假 9销假
			db("gym_order")->where(array("id" => $id))->update($data);
			$this->ajax_success("成功");
		}
	}

    /**
     * 编辑
     * @throws \think\db\exception\DataNotFoundException
     * @throws \think\db\exception\ModelNotFoundException
     * @throws \think\exception\DbException
     */
	public function member_edit()
    {
		$id=input("id");
		$shop_id=sp_get_current_shop_id();
		$model=db("GymMember")->where("shop_id=$shop_id and id=$id")->find();
		$this->assign("list1",db("GymEmployee")->where("shop_id=$shop_id and status=1 and type=2")->field("id,name")->select());
		$this->assign("model",$model);
		echo $this->fetch();	
	}

    /**
     * 编辑操作
     * @throws \think\Exception
     * @throws \think\exception\DbException
     * @throws \think\exception\PDOException
     */
	public function member_edit_post()
    {
		$id = input("id");
		if(request()->isPost()){
			$shop_id = $this->shop_id;
			$mobile=input("mobile");
			$old_mobile=input("old_mobile");
			$member_ship_id_1=input("member_ship_id_1");//修改前的
			$member_ship_id=input("member_ship_id");//修改后的
            $name = input("name/s", "");
            $sex = input("sex/d", 1);
            $id_card = input("id_card", 0);
            $come_from = input("come_from/s", "");
            $birthday = input("birthday/s", "");
            $occupation = input("occupation/s", "");
            $passport = input("passport/s", "");
            $descs = input("descs/s", "");
            $addr = input("addr/s", "");

            if (empty($name)) {
                $this->ajax_error("姓名不能为空");
            }

            if (mb_strlen($name) > 16) {
                $this->ajax_error("姓名能超过16个字符");
            }
            if (!in_array($sex, array(1, 2))) {
                $this->ajax_error("性别选择错误");
            }
            if(!preg_match("/^1[3456789]\d{9}$/", $mobile)) {
                $this->ajax_error("手机号格式不正确");
            }
            if (!preg_match("/^\d{15}|\d{18}$/", $id_card)) {
                $this->ajax_error("身份证号码格式不正确");
            }
            if (empty($member_ship_id)) {
                $this->ajax_error("请选择一个会籍");
            }
            $gym_employee = db("gym_employee")->find($member_ship_id);
            if (empty($gym_employee)) {
                $this->ajax_error("归属会籍选择错误");
            }
            if ($gym_employee["shop_id"] != $shop_id || $gym_employee["status"] != 1 || $gym_employee["type"] != 2) {
                $this->ajax_error("归属会籍选择错误");
            }
            $come_from_arr = config("come_from");
            if (!in_array($come_from, $come_from_arr)) {
                $this->ajax_error("会员来源选择错误");
            }
			
			if($mobile!=$old_mobile){
				$count=db("GymMember")->fetchsql(FALSE)->where("shop_id=$shop_id and  mobile='$mobile'")->count(1);
				if($count>0){
					return $this->ajax_error("手机号码已经存在");
				}	
			}
            db("interface")->where(array("member_id" => $id, "shop_id" => $shop_id))->setField(array("name"=>input("name"),"mobile"=>input("mobile")));
			if($member_ship_id==$member_ship_id_1){//没换会籍
			}else{
				db("GymFollowUp")->where("member_ship_id=$member_ship_id_1 and member_id=$id")->delete();
				db("GymOrder")->where("member_ship_id=$member_ship_id_1 and gym_member_id=$id and is_delete=0")->setField(array("member_ship_id"=>$member_ship_id));
				db("GymFollowUp")->insert(array(
						"member_ship_id"=>$member_ship_id,
						"member_id"=>$id,
						"type"=>1,
						"follow_up_type"=>3,
						"remarks"=>"转会籍系统添加",
						"remarks1"=>"转会籍系统添加",
						"shop_id"=>$shop_id
				));				
			}
			db("GymMember")->where("shop_id=$shop_id and id=$id")->update(array(
				"name"=>input("name"),
				"birthday"=>input("birthday"),
				"sex"=>input("sex"),
				"mobile"=>input("mobile"),
				"id_card"=>input("id_card"),
				"occupation"=>input("occupation"),
				"addr"=>input("addr"),
				"passport"=>input("passport"),
				"descs"=>input("descs"),
				"come_from"=>input("come_from"),
				"member_ship_id"=>$member_ship_id,
			));
			$this->ajax_success("成功");
		}
	}

    /**
     * 卡列表数据
     */
	public function ajax_index()
    {
		$this->ajax($this->_ajax_index());
	}

    /**
     * 获取卡数据
     * @return array
     */
	private function _ajax_index()
    {
        $card_no = input("card_no/s", "");
        $name = input("name/s", "");
        $mobile = input("mobile/s", "");
        $gym_card_type = input("gym_card_type/d", 0);
        $gym_card_id = input("gym_card_id/d", 0);
        $member_ship_id = input("member_ship_id/d", 0);
        $shop_id = $this->shop_id;
        $order_status = input("order_status/d", 0);
        $draw = input("draw",0) + 1;//请求时间

        $where["a.shop_id"] = array("eq", $shop_id);

        if (!empty($card_no)) {
            $where["b.card_no"] = array("like", "%{$card_no}%");
        }
        if (!empty($name)) {
            $where["a.name"] = array("like", "%{$name}%");
        }
        if (!empty($mobile)) {
            $where["a.mobile"] = array("like", "%{$mobile}%");
        }
        if (!empty($gym_card_type)) {
            $where["b.gym_card_type"] = array("eq", $gym_card_type);
        }
        if (!empty($gym_card_id)) {
            $where["b.gym_card_id"] = array("eq", $gym_card_id);
        }
        if (!empty($member_ship_id)) {
            $where["a.member_ship_id"] = array("eq", $member_ship_id);
        }

        $where["b.is_delete"] = array("eq", 0);

        $field = "a.id,a.name,a.mobile,a.come_from,a.member_ship_id,a.shop_id,b.id as order_id,b.gym_card_name,b.gym_card_type,b.gym_card_id,b.card_no,b.end_date,b.order_status,b.able_count,b.able_money,b.able_day,c.name as employee_name, b.is_delete";
        if (!empty($order_status)) {
            if ($order_status == 5) {
                $where["b.is_delete"] = array(array("eq", 1), null, "or");
                $where["b.order_status"] = array(array("eq", 0), null, "or");
                //已购卡会员ids
                $buy_card_ids = db("gym_order")->where(array("is_delete" => 0, "shop_id" => $shop_id))->column("gym_member_id");
                if (!empty($buy_card_ids)) {
                    $where["a.id"] = array(array("not in", $buy_card_ids), null, "or");
                }

                $total = db("gym_member")->alias("a")
                    ->join([['m_gym_order b',"a.id=b.gym_member_id","LEFT"],['m_gym_employee c',"c.id = a.member_ship_id","LEFT"]])
                    ->group("a.id")
                    ->where($where)
                    ->count(1);


                $list = db("gym_member")->alias("a")
                    ->field($field)
                    ->join([['m_gym_order b',"a.id=b.gym_member_id","LEFT"],['m_gym_employee c',"c.id=a.member_ship_id","LEFT"]])
                    ->where($where)
                    ->group("a.id")
                    ->order($this->get_order('b'))
                    ->limit($this->get_limit())
                    ->select();
                return array('pageData'=>$list,'total'=>$total,"draw"=>$draw);
            } elseif ($order_status == 6) {
                $where['b.end_date'] = array("between", [date("Y-m-d"),date("Y-m-d", strtotime("3 month"))]);
            } elseif ($order_status == 7) {
                $where['b.able_count'] = array('<=', 3);
                $where['b.gym_card_type'] = 1;
            } else {
                $where["b.order_status"] = array("eq", $order_status);
            }
        }

		$total = db("gym_member")->alias("a")
            ->join([['m_gym_order b',"a.id=b.gym_member_id","LEFT"],['m_gym_employee c',"c.id = a.member_ship_id","LEFT"]])
            ->where($where)
            ->count(1);

		$list = db("gym_member")->alias("a")
            ->field($field)
            ->join([['m_gym_order b',"a.id=b.gym_member_id","LEFT"],['m_gym_employee c',"c.id=a.member_ship_id","LEFT"]])
            ->where($where)
            ->order($this->get_order('b'))
            ->limit($this->get_limit())
            ->select();
        return array('pageData'=>$list,'total'=>$total,"draw"=>$draw);
	}

    /**
     * ajax 根据姓名和电话动态搜索会员
     */
	public function ajax_gym_member()
    {
		$shop_id = $this->shop_id;
		$key_word = input("q");
		$order_id = input("order_id/d", 0);
		if (empty($order_id)) {
            $this->ajax(array("results"=> array(),"total_count" => 0));
        }
        $order = db("gym_order")->where(array("id" => $order_id, "shop_id" => $shop_id, "is_delete" => 0))->find();
		if (empty($order)) {
            $this->ajax(array("results"=> array(),"total_count" => 0));
        }

        $members = db("gym_member")->where(array("shop_id" => $shop_id, "mobile|name" => array("like", "%{$key_word}%"), "id" => array("neq", $order["gym_member_id"])))->column("id,mobile,name");
		$list = "";
		foreach ($members as $key => $value) {
			$list[] = array("id"=>$key, "text" => $value['name'] . "--" . $value['mobile']);
		}
		$this->ajax(array("results" => $list, "total_count"=>3));
	}

	//smartgym.com/gym/GymMember/test
//	public function test(){
//		$order=db("GymOrder")->where("id=17")->find();
//		action("gym/GymOrderHistory/add_history_1",["type"=>"购卡","order"=>$order,"change"=>""]);
//		var_dump("success");
//	}
	/*新增合同记录*/
//	public function add_order_histroy($type,$order,$order_old){
//		if($type=='购卡'){
//			action("gym/GymOrderHistory/add_history_1",["order"=>$order,"order_old"=>$order_old]);
//		}elseif($type=='升级'){
//			action("gym/GymOrderHistory/add_history_2",["order"=>$order,"order_old"=>$order_old]);
//		}elseif($type=='续卡'){
//			action("gym/GymOrderHistory/add_history_3",["order"=>$order,"order_old"=>$order_old]);
//		}elseif($type=='退款重办'){
//			action("gym/GymOrderHistory/add_history_4",["order"=>$order,"order_old"=>$order_old]);
//		}elseif($type=='退会'){
//			action("gym/GymOrderHistory/add_history_5",["order"=>$order,"order_old"=>$order_old]);
//		}elseif($type=='换卡'){
//			action("gym/GymOrderHistory/add_history_6",["order"=>$order,"order_old"=>$order_old]);
//		}elseif($type=='转卡'){
//			action("gym/GymOrderHistory/add_history_7",["order"=>$order,"order_old"=>$order_old]);
//		}elseif($type=='请假'){
//			action("gym/GymOrderHistory/add_history_8",["order"=>$order,"order_old"=>$order_old]);
//		}elseif($type=='销假'){
//			action("gym/GymOrderHistory/add_history_9",["order"=>$order,"order_old"=>$order_old]);
//		}
//	}
		/**
	 * 同步会员信息到Interface 中
	 * */
//	 public function sync_member($order){
//	 	db("GymMember")->where("id=".$order['gym_member_id'])->setField(["web_open_up"=>1]);
//	 	$member=db("GymMember")->field("id,name,sex,mobile")->find($order['gym_member_id']);
//		$interface=array(
//					   			"card_no"=>$order['card_no'],
//					   			"in_varifycation"=>0,
//					   			"in_varifycation_type"=>0,
//								"start_date"=>$order["start_date"],
//								"end_date"=>$order["end_date"],
//								"mobile"=>$member["mobile"],
//								"contract_id"=>$order["order_no"],
//								"member_id"=>$order["gym_member_id"],
//								"name"=>$member["name"],
//								"surplus_num"=>$order["able_count"],
//								"membership_type"=>$order["gym_card_type"],
//								"contract_status"=>$order["order_status"],
//								"owner_type"=>1,
//								"shop_id"=>$order['shop_id'],
//			);
//		db("Interface")->insert($interface);
//	 }

    /**
     * 获取唯一order_no
     * @return string
     * @throws \think\db\exception\DataNotFoundException
     * @throws \think\db\exception\ModelNotFoundException
     * @throws \think\exception\DbException
     */
	 private function getUniqueOrderNo() {
         $is_unique = false;
	     while (!$is_unique) {
             $order_no = time() . rand(100,999);
             $is_exist = db("gym_order")->where(array("order_no" => $order_no))->find();
             if (empty($is_exist)) {
                 $is_unique = true;
             }
         }
	     return $order_no;
     }


    /**
     * 模板是否新增或者修改---做记录
     * */
    private function _model_down_record_save_update($data){
        $shop_id = $data['shop_id'];
        $card_no = $data['card_no'];
        $type = $data['type'];
        $model = db("ModelDownRecord")->where("card_no='$card_no' and shop_id=$shop_id and type=$type ")->field("id,card_no")->find();
        if (empty($model)) {
            db("ModelDownRecord")->insert(array("card_no"=>$card_no,"shop_id"=>$shop_id,"type"=>$type,"is_down"=>0));
        } else {
            db("ModelDownRecord")->where("card_no='$card_no' and shop_id=$shop_id and type=$type")->update(array("is_down"=>0,"update_time"=>date("Y-m-d H:i:s")));
        }
    }

    /**
     * 插入或者修改facecode
     * @param $data
     * @throws \think\Exception
     * @throws \think\db\exception\DataNotFoundException
     * @throws \think\db\exception\ModelNotFoundException
     * @throws \think\exception\DbException
     * @throws \think\exception\PDOException
     */
    private function _face_code_insertOrupdate($data) {
        if(empty($data)){
            return;
        }else{
            $card_no = $data["card_no"];
            $shop_id = $data['shop_id'];
            $model=db("FaceCode")->where(" card_no='$card_no' and shop_id=$shop_id")->find();
            if(empty($model)){//新增
                db("FaceCode")->insert($data);
            }else{//修改
                db("FaceCode")->update(array_merge($model,$data));
            }
            $data['type']=2;
            $data['update_time']=date("Y-m-d H:i:s");
            $this->_model_down_record_save_update($data);
            return;
        }
    }

    /**
     * 添加到历史记录
     * @param $type int 操作类型：1购卡 2升级 3续卡 4退款重办 5退会 6换卡 7转卡 8请假 9销假 10激活
     * @param $order
     * @param array $order_old
     */
    private function addOrderHistory($type, $order, $order_old = array())
    {
        $admin_id = sp_get_current_admin_id();
        $shop_id = sp_get_current_shop_id();

        $order_old["start_date"]    = empty($order_old["start_date"])   ? "0" : $order_old["start_date"];
        $order_old["end_date"]      = empty($order_old["end_date"])     ? "0" : $order_old["end_date"];
        $order_old["able_day"]      = empty($order_old["able_day"])     ? "0" : $order_old["able_day"];
        $order_old["able_count"]    = empty($order_old["able_count"])   ? "0" : $order_old["able_count"];
        $order_old["able_money"]    = empty($order_old["able_money"])   ? "0" : $order_old["able_money"];

        $order["start_date"]        = empty($order["start_date"])       ? $order_old["start_date"] : $order["start_date"];
        $order["end_date"]          = empty($order["end_date"])         ? $order_old["end_date"] : $order["end_date"];
        $order["able_day"]          = empty($order["able_day"])         ? $order_old["able_day"] : $order["able_day"];
        $order["able_count"]        = empty($order["able_count"])       ? $order_old["able_count"] : $order["able_count"];
        $order["able_money"]        = empty($order["able_money"])       ? $order_old["able_money"] : $order["able_money"];

        switch ($type) { //type: 操作类型：1购卡 2升级 3续卡 4退款重办 5退会 6换卡 7转卡 8请假 9销假 10激活
            case 1:
                $history_arr = array(
                    "opt_type"          => "购卡",
                    "order_no"          => $order['order_no'],
                    "card_no"           => $order['card_no'],
                    "shop_id"           => $shop_id,
                    "gym_member_id"     => $order['gym_member_id'],
                    "admin_id"          => $admin_id,
                    "gym_card_name"     => $order['gym_card_name'],
                    "gym_card_id"       => $order['gym_card_id'],
                    "gym_card_type"     => $order['gym_card_type'],
                    "pay_money"         => $order['pay_money'],
                    "pay_type"          => $order['pay_type'],
                    "order_date"        => $order['order_date'],
                    "member_ship_id"    => $order['member_ship_id'],
                    "descs"             => $order['descs'],
                    "gift_id"           => $order["gift_id"],
                    "gift"              => $order["gift"],
                    "order_id"          => $order["id"],
                );
                break;
            case 2:
                $history_arr = array(
                    "opt_type"          => "升级",
                    "order_no"          => $order['order_no'],
                    "card_no"           => $order_old['card_no'],
                    "shop_id"           => $shop_id,
                    "gym_member_id"     => $order_old['gym_member_id'],
                    "admin_id"          => $admin_id,
                    "gym_card_name"     => $order_old['gym_card_name'],
                    "gym_card_type"     => $order_old['gym_card_type'],
                    "pay_money"         => $order['pay_money'],
                    "pay_type"          => $order['pay_type'],
                    "order_date"        => $order['order_date'],
                    "member_ship_id"    => $order_old['member_ship_id'],
                    "descs"             => $order['descs'],
                    "order_id"          => $order_old["id"],
                );
                break;
            case 3:
                $history_arr = array(
                    "opt_type"          => "续卡",
                    "order_no"          => $order['order_no'],
                    "card_no"           => $order_old['card_no'],
                    "shop_id"           => $shop_id,
                    "gym_member_id"     => $order_old['gym_member_id'],
                    "admin_id"          => $admin_id,
                    "gym_card_name"     => $order['gym_card_name'],
                    "gym_card_id"       => $order['gym_card_id'],
                    "gym_card_type"     => $order_old['gym_card_type'],
                    "pay_money"         => $order['pay_money'],
                    "pay_type"          => $order['pay_type'],
                    "order_date"        => $order['order_date'],
                    "member_ship_id"    => $order_old['member_ship_id'],
                    "descs"             => $order['descs'],
                    "order_id"          => $order_old["id"],
                );
                break;
            case 4:
                $history_arr = array(
                    "opt_type"          => "退款重办",
                    "order_no"          => $order_old['order_no'],
                    "card_no"           => $order_old['card_no'],
                    "shop_id"           => $shop_id,
                    "gym_member_id"     => $order_old['gym_member_id'],
                    "admin_id"          => $admin_id,
                    "gym_card_name"     => $order_old['gym_card_name'],
                    "gym_card_type"     => $order_old['gym_card_type'],
                    "gym_card_id"       => $order_old['gym_card_id'],
                    "pay_money"         => -$order_old['pay_money'],
                    "pay_type"          => $order_old['pay_type'],
                    "order_date"        => $order['order_date'],
                    "member_ship_id"    => $order_old['member_ship_id'],
                    "descs"             => $order['descs'],
                    "gift"              => $order_old['gift'],
                    "order_id"          => $order_old["id"],
                );
                $history_arr["opt_type"]        = "退款重办";
                break;
            case 5:
                $history_arr = array(
                    "opt_type"          => "退会",
                    "order_no"          => $order_old['order_no'],
                    "card_no"           => $order_old['card_no'],
                    "shop_id"           => $shop_id,
                    "gym_member_id"     => $order_old['gym_member_id'],
                    "admin_id"          => $admin_id,
                    "gym_card_name"     => $order_old['gym_card_name'],
                    "gym_card_type"     => $order_old['gym_card_type'],
                    "gym_card_id"       => $order_old['gym_card_id'],
                    "pay_money"         => -$order['pay_money'],
                    "pay_type"          => $order_old['pay_type'],
                    "order_date"        => $order['order_date'],
                    "member_ship_id"    => $order_old['member_ship_id'],
                    "descs"             => $order['descs'],
                    "order_id"          => $order_old["id"],
                );
                break;
            case 6:
                $history_arr = array(
                    "opt_type"          => "换卡",
                    "order_no"          => $order['order_no'],
                    "card_no"           => $order['card_no'],
                    "old_card_no"       => $order_old['card_no'],
                    "shop_id"           => $shop_id,
                    "gym_member_id"     => $order_old['gym_member_id'],
                    "admin_id"          => $admin_id,
                    "gym_card_name"     => $order_old['gym_card_name'],
                    "gym_card_type"     => $order_old['gym_card_type'],
                    "gym_card_id"       => $order_old['gym_card_id'],
                    "pay_money"         => $order['pay_money'],
                    "pay_type"          => $order['pay_type'],
                    "order_date"        => $order['order_date'],
                    "member_ship_id"    => $order_old['member_ship_id'],
                    "descs"             => $order['descs'],
                    "order_id"          => $order_old["id"],
                );
                break;
            case 7:
                $history_arr = array(
                    "opt_type"          => "换卡(转出)",
                    "order_no"          => $order['order_no'],
                    "card_no"           => $order_old['card_no'],
                    "shop_id"           => $shop_id,
                    "gym_member_id"     => $order['gym_member_id'],
                    "old_gym_member_id" => $order_old['gym_member_id'],
                    "admin_id"          => $admin_id,
                    "gym_card_name"     => $order_old['gym_card_name'],
                    "gym_card_type"     => $order_old['gym_card_type'],
                    "gym_card_id"       => $order_old['gym_card_id'],
                    "pay_money"         => $order['pay_money'],
                    "pay_type"          => $order['pay_type'],
                    "order_date"        => $order['order_date'],
                    "member_ship_id"    => $order['member_ship_id'],
                    "descs"             => $order['descs'],
                    "order_id"          => $order_old["id"],
                );
                break;
            case 8:
                $history_arr = array(
                    "opt_type"          => "请假",
                    "order_no"          => $order['order_no'],
                    "card_no"           => $order_old['card_no'],
                    "shop_id"           => $shop_id,
                    "gym_member_id"     => $order_old['gym_member_id'],
                    "admin_id"          => $admin_id,
                    "gym_card_name"     => $order_old['gym_card_name'],
                    "gym_card_type"     => $order_old['gym_card_type'],
                    "gym_card_id"       => $order_old['gym_card_id'],
                    "pay_money"         => $order['pay_money'],
                    "pay_type"          => $order['pay_type'],
                    "order_date"        => $order['order_date'],
                    "member_ship_id"    => $order_old['member_ship_id'],
                    "descs"             => $order['descs'],
                    "order_id"          => $order_old["id"],
                );
                break;
            case 9:
                $history_arr = array(
                    "opt_type"          => "销假",
                    "order_no"          => $order_old['order_no'],
                    "card_no"           => $order_old['card_no'],
                    "shop_id"           => $shop_id,
                    "gym_member_id"     => $order_old['gym_member_id'],
                    "admin_id"          => $admin_id,
                    "gym_card_name"     => $order_old['gym_card_name'],
                    "gym_card_type"     => $order_old['gym_card_type'],
                    "gym_card_id"       => $order_old['gym_card_id'],
                    "pay_money"         => 0,
                    "pay_type"          => "其他",
                    "order_date"        => date("Y-m-d"),
                    "member_ship_id"    => $order_old['member_ship_id'],
                    "descs"             => $order_old['descs'],
                    "order_id"          => $order_old["id"],
                );
                break;
            case 10:
                $history_arr = array(
                    "opt_type"          => "激活",
                    "order_no"          => $order_old['order_no'],
                    "card_no"           => $order_old['card_no'],
                    "shop_id"           => $shop_id,
                    "gym_member_id"     => $order_old['gym_member_id'],
                    "admin_id"          => $admin_id,
                    "gym_card_name"     => $order_old['gym_card_name'],
                    "gym_card_type"     => $order_old['gym_card_type'],
                    "gym_card_id"       => $order_old['gym_card_id'],
                    "pay_money"         => 0,
                    "pay_type"          => "其他",
                    "order_date"        => date("Y-m-d"),
                    "member_ship_id"    => $order_old['member_ship_id'],
                    "descs"             => $order_old['descs'],
                    "order_id"          => $order_old["id"],
                );
                break;
            default:
                break;
        }
        $history_arr["operation_type"] = $type;
        $history_arr["start_date_desc"] = $order_old["start_date"] . " -> " . $order["start_date"];
        $history_arr["end_date_desc"] = $order_old["end_date"] . " -> " . $order["end_date"];
        $history_arr["able_day_desc"] = $order_old["able_day"] . " -> " . $order["able_day"];
        $history_arr["able_count_desc"] = $order_old["able_count"] . " -> " . $order['able_count'];
        $history_arr["able_money_desc"] = $order_old["able_money"] . " -> " . $order['able_money'];

        db("gym_order_history")->insert($history_arr);
    }

    /**
     * 激活操作
     */
    public function activateCard()
    {
        $id = input("order_id/d");
        $shop_id = $this->shop_id;

        if (empty($id)) {
            $this->ajax_error("参数错误");
        }
        $order_old = db("gym_order")->where(array("shop_id" => $shop_id, "id" => $id, "is_delete" => 0))->find();
        if (empty($order_old)) {
            $this->ajax_error("未找到该卡");
        }
        if ($order_old['order_status'] != 3 ) {
            $this->ajax_error("此卡已激活");
        }

        $new_end_date = strtotime($order_old['end_date']) - strtotime($order_old['start_date']) + time();
        $data=array(
            'start_date' => date("Y-m-d"),
            'end_date' => date("Y-m-d", $new_end_date),
            'order_status' => 1
        );
        $this->addOrderHistory(10, array_merge($order_old, $data), $order_old); //type:1购卡 2升级 3续卡 4退款重办 5退会 6换卡 7转卡 8请假 9销假 10激活
        db("gym_order")->where(array("id" => $id))->update($data);
        $this->ajax_success("成功");
    }
}
